package tliasmanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tliasmanagement.anno.Log;
import tliasmanagement.mapper.ClazzMapper;
import tliasmanagement.pojo.Clazz;
import tliasmanagement.pojo.ClazzQueryParam;
import tliasmanagement.pojo.PageResult;
import tliasmanagement.service.ClazzService;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    /**
     * 分页查询
     *
     * @param clazzQueryParam 查询参数
     */
    @Override
    public PageResult page(ClazzQueryParam clazzQueryParam) {
        // 分页查询
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> list = clazzMapper.getClazzByPage(clazzQueryParam);

        // 为每个班级设置状态
        for (Clazz clazz : list) {
            if (clazz.getEndDate() != null && LocalDateTime.now().isAfter(clazz.getEndDate().atStartOfDay())) {
                clazz.setStatus("已结课");
            } else if (clazz.getBeginDate() != null && LocalDateTime.now().isBefore(clazz.getBeginDate().atStartOfDay())) {
                clazz.setStatus("未开班");
            } else {
                clazz.setStatus("在读中");
            }
        }

        Page<Clazz> p = (Page<Clazz>) list;
        return new PageResult(p.getTotal(), p.getResult());
    }

    /**
     * 添加
     *
     * @param clazz 添加的班级
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Clazz clazz) {
        try {
            // 补全基本属性
            clazz.setCreateTime(LocalDateTime.now());
            clazz.setUpdateTime(LocalDateTime.now());
            clazzMapper.add(clazz);
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据id查询
     *
     * @param id 查询的id
     */
    @Override
    public Clazz getDetailInfo(Integer id) {
        return clazzMapper.getDetailInfo(id);
    }

    /**
     * 修改
     *
     * @param clazz 修改的班级
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    /**
     * 删除
     *
     * @param id 删除的id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        clazzMapper.delete(id);
    }

    /**
     * 查询所有班级
     * */
    @Override
    public List<Clazz> list() {
        List<Clazz> list = clazzMapper.list();
        return list;
    }

}
